package eagle.im.server2;

import eagle.im.proto.LoginModel;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

/**
 * @Program : eagle-im
 * @ClassName : ServerHandler
 * @Description :
 * @Date: 2021-12-20 18:18
 * @Version : 1.0
 */
public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接上一个客户端。。。。");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf msg) throws Exception {
        int bytes = msg.readableBytes();
        if (bytes > 0) {
            ByteBuf buf = msg.readBytes(bytes);
            int len = buf.capacity();
            byte[] buff = new byte[len];
            buf.getBytes(0, buff);
            ReferenceCountUtil.release(buf);

            System.out.println("the rec len is    " + len);
            LoginModel.LoginInfo info = LoginModel.LoginInfo.parseFrom(buff);
            System.out.println(info.getName());

            System.out.println(info.getPassword());

            System.out.println(info.getType());

            System.out.println(info.getDesc());
        }

       /* System.out.println(info.getName());

        System.out.println(info.getPassword());

        System.out.println(info.getType());

        System.out.println(info.getDesc());
*/
        LoginModel.LoginInfo infoToClient = LoginModel.LoginInfo.newBuilder()
                .setName("client : " + channelHandlerContext.channel().localAddress().toString())
                .setType(10)
                .setPassword("server to client password")
                .setDesc("aaaaaaaaaaaaaaaa").build()
                ;
       // StudentInfo.Student serverToClient= StudentInfo.Student.newBuilder();
        byte[] bytes1 = infoToClient.toByteArray();
        ByteBuf byteBuf = Unpooled.buffer();

        byteBuf.writeBytes(bytes1);
        channelHandlerContext.channel().writeAndFlush(byteBuf);
    }

}
